package com.badibadi.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.badibadi.activity.ActivityReadingActivity;
import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.ClubHomepageActivity;
import com.badibadi.activity.LogReadingActivity;
import com.badibadi.activity.LogReadingDanjiActivity;
import com.badibadi.activity.LookAtTheDetailedActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.PicturePreviewActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.activity.UpPicturesActivity;
import com.badibadi.fragment.AfterLandingMessageItem02.ViewHolder;
import com.badibadi.fragment.AfterLandingMessageItem02.XListView1Adapter____1;
import com.badibadi.infos.BrowseAllPhoto_Model;
import com.badibadi.infos.ImgShowModel;
import com.badibadi.infos.Pre_message_total;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

/**
 * //* 第四个fragment 评论 //* @author Administrator getId()
 * //*pinglun_imp_small_fragment //
 */
public class AfterLandingMessageItem03 extends BaseAppFragment implements
		IXListViewListener {
	// TODO Auto-generated method stub
	private String TAG = "AfterLandingMessageItem00";
	private XListView1Adapter____1 x1Adapter;
	private XListView xListView1;
	private int Page;
	private Results results, results2, results3;
	private List<Pre_message_total> mList;
	List<Pre_message_total> list;
	// FinalBitmap finalBitmap;
	private int pageNum = 6;
	private DisplayImageOptions options;
	private ImgShowModel imgShowModel;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				try {
					xListView1.requestLayout();
					mList.addAll(list);
					x1Adapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
			case 5:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xb12));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 6:
				Utils.ExitPrgress(getActivity());

				try {
					// imgShowModel
					if (imgShowModel != null) {
						Intent intent1 = new Intent(getActivity(),
								PicturePreviewActivity.class);
						List<BrowseAllPhoto_Model> list = new ArrayList<BrowseAllPhoto_Model>();
						BrowseAllPhoto_Model br = new BrowseAllPhoto_Model();
						br.setId(imgShowModel.getId());
						br.setPath(imgShowModel.getPath());
						list.add(br);
						intent1.putExtra("picture_list", (Serializable) list);
						startActivity(intent1);
					}

					onLoad();
					// Utils.showMessage(getActivity(), "");
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			default:
				break;
			}
		}
	};
	private String uid;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mList = new ArrayList<Pre_message_total>();
		x1Adapter = new XListView1Adapter____1();
		// finalBitmap=FinalBitmap.create(getActivity());
		uid = getArguments().getString("uid");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.xlistview, null);
		InitMyXListView1(view);
		return view;
	}

	public void InitMyXListView1(View view) {
		Page = 0;
		Constants.Invite_handler = mHandler;
		xListView1 = (XListView) view.findViewById(R.id.my_xListView1);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		xListView1.startLoadMore();
	}

	private void LoadingMessage(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<Pre_message_total>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("type", "discuss");
				map.put("page", page);
				map.put("pageNum", pageNum);
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "message_total");
				//    
				if (invite_content != null) {
					results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
//								"Index/message_total解析出来的数据:"
//										+ results.getRetmsg());
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Pre_message_total.class);

							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
							mHandler.sendEmptyMessage(3);
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	protected void onLoad() {
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
	}

	// //getId()
	class XListView1Adapter____1 extends BaseAdapter {
		// private DisplayImageOptions options;

		public XListView1Adapter____1() {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getCount() {

			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {// message
			int imageWH = 55;
			LayoutInflater mInflater = LayoutInflater.from(getActivity());

			ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.pinglun_imp_small_fragment, parent, false);
				holder = new ViewHolder();
				holder.nickName = (TextView) convertView
						.findViewById(R.id.nickName);
				holder.nickName2 = (TextView) convertView
						.findViewById(R.id.nickName2);
				// message
				holder.head = (ImageView) convertView.findViewById(R.id.head);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.table = (TextView) convertView.findViewById(R.id.table);
				holder.name_title_content = (TextView) convertView
						.findViewById(R.id.name_title_content);
				holder.is_reply = (TextView) convertView
						.findViewById(R.id.is_reply);
				holder.message = (TextView) convertView
						.findViewById(R.id.message);
				holder.jump = (LinearLayout) convertView
						.findViewById(R.id.jump);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			// 昵称
			holder.nickName.setText("" + mList.get(position).getNickName());
			holder.nickName2.setText("" + mList.get(position).getNickName());
			// //头像
			// finalBitmap.display(holder.head,
			// Constants.BadiDownImgUrl+"/"+mList.get(position).getHead(),DisplayUtil.dip2px(getActivity(),
			// imageWH),DisplayUtil.dip2px(getActivity(), imageWH));
			if (!StringUtil.isNullOrEmpty(mList.get(position).getHead())) {
				try {
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl + "/"
									+ mList.get(position).getHead()
									+ Constants.appPhoto4img, holder.head,
							options);
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.noimage);
				holder.head.setImageBitmap(bmp);
			}
			// 发布时间
			try {
				holder.time.setText(""
						+ CalendarTools.getTimeChangeToString(getActivity(),
								mList.get(position).getTime()));
			} catch (Exception e) {
				// TODO: handle exception
			}

			// //1是回复，0是评论
			if (mList.get(position).getIs_reply().equals("0")) {//is_reply
				holder.is_reply.setText(getResources().getString(
						R.string.wx_pinglun));

				// holder.message.setText(""+mList.get(position).getMessage());
				if (mList.get(position).getTable().equals("activity")) {
					holder.table.setText(getResources().getString(
							R.string.wx_activity));
					jump(0, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("photo_img")) {
					holder.table.setText(getResources().getString(
							R.string.wx_zhaopian));
					jump(1, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("photo")) {
					holder.table.setText(getResources().getString(
							R.string.wx_xiangce));
					jump(2, holder.jump, mList, position);
				} else if (mList.get(position).getTable()
						.equals("humor_trends")) {
					holder.table.setText(getResources().getString(
							R.string.wx_dongtai));
					jump(3, holder.jump, mList, position);
				} else if (mList.get(position).getTable()
						.equals("record_article")) {
					holder.table.setText(getResources().getString(
							R.string.wx_record));
					jump(4, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("club")) {
					holder.table.setText(getResources().getString(
							R.string.wx_club));
					jump(5, holder.jump, mList, position);
				}
				// 活动内容
				// holder.name_title_content.setText(""+mList.get(position).getName_title_content());
				new HtmlUtils(getActivity(), holder.name_title_content, ""
						+ mList.get(position).getMessage()).showTextView();

				new HtmlUtils(getActivity(), holder.message, ""
						+ mList.get(position).getName_title_content())
						.showTextView();// 评论的什么内容

			}// 回复
			else if (mList.get(position).getIs_reply().equals("1")) {
				// 被赞的记录名字

				// 评论
				holder.is_reply.setText(getResources().getString(
						R.string.wx_reply));
				holder.table.setText(getResources().getString(
						R.string.wx_xiaoxi));
				// holder.name_title_content.setText(""+mList.get(position).getUmessage());
				new HtmlUtils(getActivity(), holder.name_title_content, ""
						+ mList.get(position).getUmessage()).showTextView();

				// 好友回复的消息
				// holder.message.setText(""+mList.get(position).getMessage());
				new HtmlUtils(getActivity(), holder.message, ""
						+ mList.get(position).getMessage()).showTextView();

				if (mList.get(position).getTable().equals("activity")) {
					jump(0, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("photo_img")) {
					jump(1, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("photo")) {
					jump(2, holder.jump, mList, position);
				} else if (mList.get(position).getTable()
						.equals("humor_trends")) {
					jump(3, holder.jump, mList, position);
				} else if (mList.get(position).getTable()
						.equals("record_article")) {
					jump(4, holder.jump, mList, position);
				} else if (mList.get(position).getTable().equals("club")) {
					jump(5, holder.jump, mList, position);
				}

			}
			holder.head.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			holder.nickName.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			holder.nickName2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			return convertView;
		}
	}

	static class ViewHolder {
		public LinearLayout jump;
		// 创立
		public ImageView head;// 用户的头像
		public TextView nickName;// 用户的昵称
		public TextView nickName2;// 用户的昵称
		public String uid;// 用户id
		public String firends;// 共同的好友
		public TextView motto;// 用户个性说明
		public String cid;// 俱乐部的id
		public TextView name;// 俱乐部的名字
		public TextView typeName;// 俱乐部的类型
		public TextView time;// 操作时间
		public String is_show;// 是否查看过 0：未查看，1：已查看
		// praise 的属性 赞
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		public TextView type;// 被赞的类型 activity photo_img humor_trends photo
								// record_article club
		public String id;// 被赞的记录id
		public TextView name_title_content;// 被赞的记录名字
		// public String is_show;//是否查看过 0：未查看，1：已查看

		// %%%%% discuss 的属性评论

		public TextView is_reply;// 1表示回复评论 0表示评论
		// public String id;//回复我的 评论的id
		public TextView message;// 回复内容
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		// public String is_show;//是否查看过 0：未查看，1：已查看
		// 第二种 评论
		// public String is_reply;//1表示回复评论 0表示评论
		public TextView table;// 评论的什么类型 activity photo_img humor_trends photo
								// record_article club
		// public String name_title_content;//对应类型的记录名字
		// public String id;//对应类型的记录id
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		// public String is_show;//是否查看过 0：未查看，1：已查看
		public String umessage;// 我的评论内容
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		mList = new ArrayList<Pre_message_total>();
		LoadingMessage(Page);
	}

	public void jump(final int i, LinearLayout jump,
			final List<Pre_message_total> mList2, final int position) {

		jump.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (i) {
				case 0:// 活动阅
					try {
						Intent intent = new Intent(getActivity(),
								ActivityReadingActivity.class);
						intent.putExtra("actId", mList2.get(position).getId());
						startActivity(intent);
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 1:// 图片预览
					try {
						imgShow(mList2.get(position).getId());
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 2:// 相册
					try {
						Intent intent2 = new Intent(getActivity(),
								UpPicturesActivity.class);
						intent2.putExtra("photoid", mList2.get(position)
								.getId());
						startActivity(intent2);
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 3:// 详细动态
					try {
						Intent intent3 = new Intent(getActivity(),
								LookAtTheDetailedActivity.class);
						intent3.putExtra("trendsId", mList2.get(position)
								.getId());
						startActivity(intent3);
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 4:// 记录阅读
					try {
						Intent intent4 = new Intent(getActivity(),
								LogReadingDanjiActivity.class);
						intent4.putExtra("aid", mList2.get(position).getId());
						startActivity(intent4);
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 5:// 俱乐部主页
					try {
						Intent intent5 = new Intent(getActivity(),
								ClubHomepageActivity.class);
						intent5.putExtra("cid", mList2.get(position).getId());
						startActivity(intent5);
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;

				}
			}
		});
	}

	// if (mList.get(position).getTable().equals("activity")) {
	// holder.table.setText("活动");
	// jump(0, holder.jump, mList, position);
	// } else if (mList.get(position).getTable().equals("photo_img")) {
	// holder.table.setText("照片");
	// jump(1, holder.jump, mList, position);
	// } else if (mList.get(position).getTable().equals("photo")) {
	// holder.table.setText("相册");
	// jump(2, holder.jump, mList, position);
	// } else if (mList.get(position).getTable()
	// .equals("humor_trends")) {
	// holder.table.setText("动态");
	// jump(3, holder.jump, mList, position);
	// } else if (mList.get(position).getTable()
	// .equals("record_article")) {
	// holder.table.setText("记录");
	// jump(4, holder.jump, mList, position);
	// } else if (mList.get(position).getTable().equals("club")) {
	// holder.table.setText("俱乐部");
	// jump(5, holder.jump, mList, position);
	// }
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		LoadingMessage(++Page);
	}

	/**
	 * 图片的id
	 * 
	 * @param imgId
	 */
	private void imgShow(final String imgId) {
		// TODO Auto-generated method stub
		// imgInfo
		//
		// Utils.showPrgress(PicturePreviewActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// list= new ArrayList<Pre_message_total>();

				String languageType = Dialog
						.getSystemLanguageType(getActivity());
				// String content = Utils.getRequest(Constants.BadiUrl_1+
				// "photo/imgInfo?imgId="+imgId+"&languageType="+languageType);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(getActivity()));
				map.put("imgId", imgId);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "Image/imgShow");
				//    
				if (content != null) {
					results3 = Utils.checkResult_NNN(getActivity(), content);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")
							&& results3.isRet() == true) {
//						   
						try {
							imgShowModel = JSONUtils.getEntityByJsonString(
									results3.getRetmsg(), ImgShowModel.class);

							mHandler.sendEmptyMessage(6);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {

						mHandler.sendEmptyMessage(5);
					}
				} else {

					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}
}